<?php

namespace Beerus\Modules\DecoCalculator\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\excel\DownExcel;
use Doraemon\model\DecoCalculator\DecoCalculatorWhite;
use Doraemon\model\DecoCalculator\DecoCalculatorWhite as mDecoCalculatorWhite;
use Doraemon\model\DecoCompany;
use Doraemon\model\DecoCompanyAuth as mDecoCompanyAuth;
use Doraemon\model\Member;
use Doraemon\service\DecoCompany\Schedule as sSchedule;
use Doraemon\service\es\EsDecoCompany;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Beerus\Modules\DecoCalculator\Actions\deleteWhite;
use Beerus\Modules\DecoCalculator\Actions\topWhiteDeco;
use Beerus\Modules\DecoCalculator\Actions\hiddenTopWhite;

class WhiteController
{
    const CITY_WHITE_MAX = 5;

    // 列表
    public function index(Request $request,Content $content) {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $params = $request->all();

        $conditions = [
            'data_status' => mDecoCalculatorWhite::STATUS_NORMAL,
        ];

        if (!empty($params['uid'])) {
            $conditions['uid'] = $params['uid'];
        }

        if (!empty($params['nick'])) {
            $uid = User::getUidByNick($params['nick']);
            $conditions['uid'] = $uid;
        }

        if (!empty($params['city_id'])) {
            // es取地区装修公司
            $extParams = array(
//                "service_area" => Area::locationId2location($params['city_id']),
	            "service_area" => Region::getNameByCode($params['city_id']) ?? '',
                "auth_status" => mDecoCompanyAuth::AUTH_STATUS_SUCCESS,
            );
            $es_company = EsDecoCompany::getList(1, 10000, $extParams);
            $conditions['uid'] = $es_company['rows'];
        }

        $total = mDecoCalculatorWhite::countByCondition($conditions);

        $conditions['LIMIT'] = [($page - 1) * $pageSize, $pageSize ];

        $list = mDecoCalculatorWhite::listByCondition($conditions);

        if ($list) {
            $user_ids = array_column($list, 'uid');
            $member_info = Member::getUsers($user_ids);
        }

        foreach ($list as $key => &$item) {
            $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];

            $company = DecoCompany::getByUid($item['uid']);
//            $lids = explode(',', $company['main_area']);
//            $city_id = end($lids);
//            $item['city'] = Area::locationId2location($city_id);
	        $item['city'] = $company['main_area_name'];
        }

        // 按城市排序
        //置顶排序
        $top_list = array_column($list, 'is_top');
        $topTimeList = array_column($list, 'top_time');
        $city_list = array_column($list, 'city');
        array_multisort($top_list,SORT_ASC,$topTimeList,SORT_DESC,$city_list, SORT_ASC, $list);

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);

        $search_params = http_build_query($conditions);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->setActionClass(DropdownActions::class);

                // 添加导出按钮
                $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                    $url = url('/admin/DecoCalculator/white/export?'. $search_params);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出白名单列表</span></a>
                    </div>';
                    $tool->append($button);
                });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('city_id', '城市')->select(mDecoCalculatorWhite::CITY_MAP);
                    });

                    $filter->expand();
                });

                $grid->column("id", 'ID');
                $grid->column("city", '城市');
                $grid->column("uid", '用户ID');
                $grid->column("nick", '用户昵称');
                $grid->column("remarks", '备注');
                $grid->column("is_top", '是否置顶')->display(function () {
                    if ($this->is_top == DecoCalculatorWhite::HAVE_TOP){
                        return "已置顶";
                    }else{
                        return "未置顶";
                    }
                });
                $grid->column("add_time", '创建时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->add_time);
                });
                $grid->column("edit_time", '修改时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edit_time);
                });
                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name ?: $this->admin_name;
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->disableEdit();
                    $actions->add(new deleteWhite);
                    $id = $actions->row->id;
                    //判断信息
                    $whiteInfo = DecoCalculatorWhite::getByCondition(["id" => $id]);
                    if ($whiteInfo['is_top'] == DecoCalculatorWhite::HIDDEN_TOP){
                        $actions->add(new topWhiteDeco);
                    }else{
                        $actions->add(new hiddenTopWhite);
                    }

                });
            });

        $tab = new Tab();
        $tab->add('装修公司白名单配置列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('装修公司白名单配置列表')
            ->description(' ')
            ->breadcrumb(['text' => '装修公司白名单配置列表']);
    }

    // 编辑
    public function edit(Content $content, $id = 0)
    {
        if($id == 0) {
            return $content
                ->header('装修公司白名单配置 - 新增')
                ->breadcrumb([
                    'text' => '装修公司白名单配置列表',
                    'url' => '/DecoCalculator/white/',
                ])
                ->body(self::editAction($id));
        } else {
            return $content
                ->header('装修公司白名单配置 - 编辑')
                ->breadcrumb([
                    'text' => '装修公司白名单配置列表',
                    'url' => '/DecoCalculator/white/',
                ])
                ->body(self::editAction($id));
        }
    }

    public function editAction($id)
    {
        if($id == 0) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = mDecoCalculatorWhite::getByCondition(['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        }

        $form->text('uid', '装修公司uid')->required()->pattern('^([1-9][0-9]*){1,10}$')->setWidth(4, 2);
        $form->text('remarks', '备注')->attribute('maxlength', 50)->setWidth(4, 2);
        $form->action('/admin/DecoCalculator/white/save');
        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        try {
            $params = $request->all();
            // 已认证装修公司
            $auth_info = mDecoCompanyAuth::getByUid($params['uid']);
            if (empty($auth_info) || $auth_info['auth_status'] != mDecoCompanyAuth::AUTH_STATUS_SUCCESS) {
                throw new \Exception("该uid不是已认证装修公司");
            }

            // uid已存在
            $uid_white = mDecoCalculatorWhite::getByCondition(['uid' => $params['uid']]);
            if ($uid_white) {
                throw new \Exception("该uid已存在，请勿重复添加");
            }

            $data = [
                'uid' => $params['uid'],
                'remarks' => $params['remarks'],
                'admin_id' => Admin::user()->id,
                'admin_name' => Admin::user()->find(Admin::user()->id)->name,
                'add_time' => time(),
            ];
            mDecoCalculatorWhite::addInfo($data);

            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/DecoCalculator/white')->with(compact('success'));

        }  catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delete($id)
    {
        $update_data = [
            'data_status' => mDecoCalculatorWhite::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
        ];
        if (!mDecoCalculatorWhite::updateInfo($update_data, ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }

    public function export(Request $request)
    {
        $params = $request->all();

        $conditions = [
            'data_status' => mDecoCalculatorWhite::STATUS_NORMAL,
        ];

        if (!empty($params['uid'])) {
            $conditions['uid'] = $params['uid'];
        }

        if (!empty($params['nick'])) {
            $uid = User::getUidByNick($params['nick']);
            $conditions['uid'] = $uid;
        }

        if (!empty($params['city_id'])) {
            // es取地区装修公司
            $extParams = array(
//                "service_area" => Area::locationId2location($params['city_id']),
                "service_area" => Region::getNameByCode($params['city_id']) ?? '',
                "auth_status" => mDecoCompanyAuth::AUTH_STATUS_SUCCESS,
            );
            $es_company = EsDecoCompany::getList(1, 10000, $extParams);
            $conditions['uid'] = $es_company['rows'];
        }

        $list = mDecoCalculatorWhite::listByCondition($conditions);

        if ($list) {
            $user_ids = array_column($list, 'uid');
            $member_info = Member::getUsers($user_ids);
        }

        $data = [];
        foreach ($list as $key => $item) {
            $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];

            $company = DecoCompany::getByUid($item['uid']);
//            $lids = explode(',', $company['main_area']);
//            $city_id = end($lids);
//            $item['city'] = Area::locationId2location($city_id);

            $data[] = [
                'city' => $company['main_area_name'],
                'uid' => $item['uid'],
                'nick' => $item['nick'],
                'remarks' => $item['remarks'],
                'add_time' => date('Y-m-d H:i:s', $item['add_time']),
                'edit_time' => date('Y-m-d H:i:s', $item['edit_time']),
                'admin_name' => Admin::user()->find($item['admin_id'])->name ?: $item['admin_name'],
            ];
        }

        // 按城市排序
        $city_list = array_column($data, 'city');
        array_multisort($city_list, SORT_ASC, $data);

        // 设置列宽
        $letter = range('A', 'N');
        $header = [
            '城市', '用户id', '用户昵称', '备注', '创建时间', '修改时间', '操作人'
        ];
        $excel = new DownExcel();
        $excel->setFileName('装修公司订单表 - ' . date('YmdHis'));
        $excel->setSheetTitle('装修公司订单表');

        // 设置列宽
        $width = [
            'A' => 12,
            'B' => 15,
            'C' => 20,
            'D' => 30,
            'E' => 30,
            'F' => 30,
            'G' => 15,
        ];

        $excel->setWidth($width);
        $excel->setDefaultStyleAlignment();

        foreach ($header as $key => $value) {
            // 设置字体
            $excel->setFrontName($letter[$key]);
            // 设置加粗
            $excel->setFrontBold("$letter[$key]1");
            // 设置大小
            $excel->setFrontSize($letter[$key]);
        }

        $excel->create($data, $header);
    }
}
